<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/8/22
 * Time: 15:10
 * 活动定时任务脚本
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Exception;

class Timing extends Controller{

    /***
     * 活动状态未开始变成报名中
     */
    public function updateActivity(){
        $where['activity_sh'] = 1;
        $where['activity_status'] = 1;
        //所有符合的审核通过，未开始的活动
        $list = Db::table('up_institutional_activities')
            ->field('activity_mechanism_id,id,activity_name,
            activity_start_time,activity_end_time,activity_sign_start,activity_sign_end')
            ->where($where)->select();
        $now_time = time();//当前时间戳
        foreach ($list as $key=>$vo){
            if(strtotime($vo['activity_sign_start'])>0&&strtotime($vo['activity_sign_end'])>0){//设置了活动报名时间
                if(strtotime($vo['activity_sign_start'])<$now_time
                    &&$now_time<strtotime($vo['activity_sign_end'])){
                    Db::table('up_institutional_activities')->where('id',$vo['id'])->setField('activity_status',2);
                    $is_show = Db::table('up_institutional_activities')->where('id',$vo['id'])->field('is_show')->find();
                    if($is_show['is_show']==2){//改变活动显示
                        Db::table('up_institutional_activities')->where('id',$vo['id'])->setField('is_show',1);
                    }
                }
            }else{//没有设置活动报名时间
                $before_time = strtotime($vo['activity_start_time'])-3600*24;
                if($before_time<$now_time&&$now_time<strtotime($vo['activity_start_time'])){
                    Db::table('up_institutional_activities')->where('id',$vo['id'])->setField('activity_status',2);
                    $is_show = Db::table('up_institutional_activities')->where('id',$vo['id'])->field('is_show')->find();
                    if($is_show['is_show']==2){//改变活动显示
                        Db::table('up_institutional_activities')->where('id',$vo['id'])->setField('is_show',1);
                    }
                }
            }
        }
    }

    /***
     * 活动空白期
     */
    public function updateStatus(){
        $where['activity_sh'] = 1;
        $where['activity_status'] = 2;
        //所有符合的审核通过，未开始的活动
        $list = Db::table('up_institutional_activities')
            ->field('activity_mechanism_id,id,activity_name,
            activity_start_time,activity_end_time,activity_sign_start,activity_sign_end')
            ->where($where)->select();
        $now_time = time();//当前时间戳
        foreach ($list as $key=>$vo){
            if(strtotime($vo['activity_sign_start'])>0&&strtotime($vo['activity_sign_end'])>0){//设置了活动报名时间
                    if(strtotime($vo['activity_sign_end'])!=strtotime($vo['activity_start_time'])){//空白期
                        if(strtotime($vo['activity_sign_end'])<$now_time&&$now_time<strtotime($vo['activity_start_time'])){
                            Db::table('up_institutional_activities')->where('id',$vo['id'])->setField('activity_status',5);
                        }
                    }
            }
        }
    }
    /***
     * 活动开始提醒
     */
    public function index(){
        $where['activity_sh'] = 1;
        $where['activity_status'] =array('IN',array(2,5));
        //所有符合的审核通过，未开始的活动
        $list = Db::table('up_institutional_activities')
            ->field('activity_mechanism_id,id,activity_name,
            activity_start_time,activity_end_time,activity_sign_start,activity_sign_end')
            ->where($where)->select();
        $now_time = time();//当前时间戳
        foreach ($list as $key=>$vo){
            $before_time = strtotime($vo['activity_start_time'])-3600*24;
            if($before_time<$now_time&&$now_time<strtotime($vo['activity_start_time'])){
                $this->activity($vo);
            }
//            if(strtotime($vo['activity_sign_start'])>0&&strtotime($vo['activity_sign_end'])>0){//设置了活动报名时间
//                if(strtotime($vo['activity_sign_start'])<$now_time
//                    &&$now_time<strtotime($vo['activity_sign_end'])){
//                    $this->activity($vo);
//                }
//            }else{//没有设置活动报名时间
//                $before_time = strtotime($vo['activity_start_time'])-3600*24;
//                if($before_time<$now_time&&$now_time<strtotime($vo['activity_start_time'])){
//                    $this->activity($vo);
//                }
//            }
        }
    }

    /**
     * @param $vo
     * 活动报名消息通知方法
     */
    protected function activity($vo){

        //查询这个活动是否已经显示了

        //查询活动参加的人数
        $member =Db::table('up_institutional_activities_member')->where('institutional_activities_id',$vo['id'])->select();
        if(count($member)>0){//已经有人报名了
            $whereMap['n_type'] = 3;
            $whereMap['n_activitie'] = $vo['id'];
            $res = Db::table('up_notice')->where($whereMap)->find();//查询这个消息是否已经添加
            if(!$res['n_id']){//证明没有添加消息
                $data['n_createtime'] =date('Y-m-d H:i:s',time());
                $data['n_title'] ="您报名的".$vo['activity_name']."将于".date('Y-m-d H:i',strtotime($vo['activity_start_time']))."开始,请准时参加";
                $data['n_read_user'] =',0,';
                $data['n_clear_user'] =',0,';
                $data['n_user_id'] =',0,'.implode(',',array_column($member,'user_id')).',';
                $data['n_activitie'] =$vo['id'];
                $data['n_mechanism'] =$vo['activity_mechanism_id'];
                $data['n_type'] =3;
                //插入消息表里面
                Db::table('up_notice')->insertGetId($data);
                //todo  缺少极光推送
                $user_ids = array_column($member, 'user_id');
                $list = [];
                foreach($user_ids as $k=>$v){
                    $va = (string)$v;
                    array_push($list, $va);
                }
                $msg = '您报名的' . $vo['activity_name'] . '将于' . date('Y-m-d H:i',strtotime($vo['activity_start_time'])) . '开始，请准时参加';
                try{
                    $this->Jpush(1, $list, '活动开始提醒', ['type'=>1], $msg, 2);
                }catch(\Exception $e){
                    
                }
            }else{//添加了
                foreach ($member as $kk=>$vv){
                    $str = '';
                    $uid = ','.$vv['user_id'].',';
                    if(strpos($res['n_user_id'],$uid) !==false){
                        unset($member[$kk]);
                    }else{
                        $str = $res['n_user_id'].$vv['user_id'].',';
                        //更新发送
                        Db::table('up_notice')->where('n_id',$res['n_id'])->setField('n_user_id',$str);
                        //todo 缺少极光推送
                    }
                }
                $user_ids = explode(',', trim($str, ','));
                $list = [];
                foreach($user_ids as $k=>$v){
                    $va = (string)$v;
                    array_push($list, $va);
                }
                $msg = '您报名的' . $vo['activity_name'] . '将于' . date('Y-m-d H:i',strtotime($vo['activity_start_time'])) . '开始，请准时参加';
                try{
                    $this->Jpush(1, $list, '活动开始提醒', ['type'=>1], $msg, 2);
                }catch(\Exception $e){
                    
                }
            }
        }
    }


    /***
     * 活动开始签到提醒
     */
    public function ActivityStart(){
        $where['activity_sh'] = 1;
        $where['activity_status'] =array('IN',array(2,3,5));
        //所有符合的审核通过，未开始的活动
        $list = Db::table('up_institutional_activities')
            ->field('activity_mechanism_id,id,activity_name,
            activity_start_time,activity_end_time')
            ->where($where)->select();
        $now_time = time();//当前时间戳
        foreach ($list as $key=>$vo){
            $sign_time = strtotime($vo['activity_start_time']) - 7200;//签到的前2个小时

            if($sign_time<$now_time&&$now_time<strtotime($vo['activity_start_time'])){
                $where1['institutional_activities_id'] = $vo['id'];
                //查询报名没有签到的
                $user_id =  Db::table('up_institutional_activities_member')->whereNull('sign_time')->where($where1)->select();
                $whereMap['n_type'] = 4;
                $whereMap['n_activitie'] = $vo['id'];
                $resList = Db::table('up_notice')->where($whereMap)->find();//查询这个消息是否已经添加
                if(!$resList['n_id']){//证明没有添加消息
                    $data['n_createtime'] =date('Y-m-d H:i:s',time());
                    $data['n_title'] ="您报名的".$vo['activity_name']."已经开始签到了，快去签到吧";
                    $data['n_read_user'] =',0,';
                    $data['n_clear_user'] =',0,';
                    $data['n_user_id'] =',0,'.implode(',',array_column($user_id,'user_id')).',';
                    $data['n_activitie'] =$vo['id'];
                    $data['n_mechanism'] =$vo['activity_mechanism_id'];
                    $data['n_type'] =4;
                    //插入消息表里面
                    Db::table('up_notice')->insertGetId($data);
                    //todo  缺少极光推送
                    $user_ids = array_column($user_id, 'user_id');
                    $list = [];
                    foreach($user_ids as $k=>$v){
                        $va = (string)$v;
                        array_push($list, $va);
                    }
                    $msg = '您报名的' . $vo['activity_name'] . '已经开始签到了，快去签到吧';
                    try{
                        $this->Jpush(1, $list, '活动签到', ['type'=>1], $msg, 2);
                    }catch(\Exception $e){
                        
                    }
                }else{//添加了
                    foreach ($user_id as $kk=>$vv){
                        $str = '';
                        $uid = ','.$vv['user_id'].',';
                        if(strpos($resList['n_user_id'],$uid) !==false){
                            unset($user_id[$kk]);
                        }else{
                            $str = $resList['n_user_id'].$vv['user_id'].',';
                            //更新发送
                            Db::table('up_notice')->where('n_id',$resList['n_id'])->setField('n_user_id',$str);
                            //todo 缺少极光推送
                        }
                    }
                    $user_ids = explode(',', trim($str, ','));
                    $list = [];
                    foreach($user_ids as $k=>$v){
                        $va = (string)$v;
                        array_push($list, $va);
                    }
                    $msg = '您报名的' . $vo['activity_name'] . '已经开始签到了，快去签到吧';
                    try{
                        $this->Jpush(1, $list, '活动签到', ['type'=>1], $msg, 2);
                    }catch(\Exception $e){
                        
                    }
                }
            }

        }
    }

    /**
     * 活动自动变成进行中
     */
    public function have(){
        $where['activity_sh'] = 1;
        $where['activity_status'] = array('IN',array(2,5));
        //所有符合的审核通过，未开始的活动
        $list = Db::table('up_institutional_activities')
            ->field('activity_mechanism_id,id,activity_name,
            activity_start_time,activity_end_time,activity_sign_start,activity_sign_end')
            ->where($where)->select();
        $now_time = time();//当前时间戳
        foreach ($list as $key=>$vo){
            if(strtotime($vo['activity_start_time'])>0&&strtotime($vo['activity_end_time'])>0){//设置了活动报名时间
                if(strtotime($vo['activity_start_time'])<$now_time
                    &&$now_time<strtotime($vo['activity_end_time'])){
                    Db::table('up_institutional_activities')->where('id',$vo['id'])->setField('activity_status',3);
                }
            }
        }
    }

    /**
     * 活动自动变成结束
     */
    public function end(){
        $where['activity_sh'] = 1;
        $where['activity_status'] = 3;
        //所有符合的审核通过，未开始的活动
        $list = Db::table('up_institutional_activities')
            ->field('activity_mechanism_id,id,activity_name,
            activity_start_time,activity_end_time,activity_sign_start,activity_sign_end')
            ->where($where)->select();
        $now_time = time();//当前时间戳
        foreach ($list as $key=>$vo){
            if(strtotime($vo['activity_end_time'])>0){//设置了活动报名时间
                if($now_time>strtotime($vo['activity_end_time'])){
                    Db::table('up_institutional_activities')->where('id',$vo['id'])->setField('activity_status',4);
                }
            }
        }
    }
    
    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras, $msg, $code)
    {
//        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush')['appKey'],config('jpush')['masterSecret']);
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        if($msg!=''){
            $push->message($msg, [
//            'title' => 'Hello',
                'content_type' => 'text',
                'extras' => [
                    'key' => $code
                ]
            ]);
        }
        return $push->send();
    }
}